package com.maotai.llzhou.thread;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.http.client.config.RequestConfig;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maotai.llzhou.bean.CustomName;
import com.maotai.llzhou.bean.MaotaiString;
import com.maotai.llzhou.bean.MaotaiWebCookie;
import com.maotai.llzhou.bean.Product741;
import com.maotai.llzhou.service.MaotaiService;
import com.maotai.llzhou.util.HttpClientUtilNew;
import com.maotai.llzhou.util.IPFactory;

/**
 * 登录并且抢购
 */
public class MaotaiUpdateAddressThread extends Thread {

	@Resource(name = "maotaiService")
	private MaotaiService maotaiService;
	private Map<String, Object> zhanghao;
	private String ipAndPort;
	private MaotaiWebCookie mwc;
	private Map<String, Object> addrMap;


	public MaotaiUpdateAddressThread(MaotaiService maotaiService,
			Map<String, Object> zhanghao, String ipAndPort,
			MaotaiWebCookie mwc, Map<String, Object> addrMap) {
		super();
		this.maotaiService = maotaiService;
		this.zhanghao = zhanghao;
		this.ipAndPort = ipAndPort;
		this.mwc = mwc;
		this.addrMap = addrMap;
	}

	public Map<String, Object> getAddrMap() {
		return addrMap;
	}

	public void setAddrMap(Map<String, Object> addrMap) {
		this.addrMap = addrMap;
	}

	public MaotaiWebCookie getMwc() {
		return mwc;
	}

	public void setMwc(MaotaiWebCookie mwc) {
		this.mwc = mwc;
	}

	public String getIpAndPort() {
		return ipAndPort;
	}

	public void setIpAndPort(String ipAndPort) {
		this.ipAndPort = ipAndPort;
	}

	public MaotaiService getMaotaiService() {
		return maotaiService;
	}

	public void setMaotaiService(MaotaiService maotaiService) {
		this.maotaiService = maotaiService;
	}

	public Map<String, Object> getZhanghao() {
		return zhanghao;
	}

	public void setZhanghao(Map<String, Object> zhanghao) {
		this.zhanghao = zhanghao;
	}

	@Override
	public void run() {
		try {
			String addressId = zhanghao.get("addressId")+"";
			String memberId = zhanghao.get("memberId")+"";
			if(zhanghao.get("phone")==null){
				addrMap.put("usestatus", "0");
				maotaiService.updateAddressLibraryStatus(addrMap);
				zhanghao.put("yuyuestatus", "0");
				maotaiService.updateZhanghaoYuYueStatus(zhanghao);
				return;
			}
			HttpClientUtilNew hcu = HttpClientUtilNew.getInstance();
			// 增加代理
			RequestConfig config = IPFactory.getKdRequestConfig(ipAndPort);
			
			//查询预约情况
			String apply_query_url = MaotaiString.APPLY_QUERY_URL.replace("xxx", memberId);
			mwc = hcu.sendHttpGetProxy(apply_query_url, mwc, config, MaotaiString.APPLY_QUERY_REFERER);
			System.out.println(zhanghao.get("code")+" "+"账号查询预约情况--"+mwc.getContent());
			if(mwc.getContent().contains("login")){
				addrMap.put("usestatus", "0");
				maotaiService.updateAddressLibraryStatus(addrMap);
				zhanghao.put("yuyuestatus", "0");
				maotaiService.updateZhanghaoYuYueStatus(zhanghao);
				zhanghao.put("loginstatus", "0");
				maotaiService.updateZhanghaoLoginStatus(zhanghao);
				return;
			}
			if(mwc.getContent().contains("错误")){
//				zhanghao.put("loginstatus", "0");
//				maotaiService.updateZhanghaoLoginStatus(zhanghao);
				addrMap.put("usestatus", "0");
				maotaiService.updateAddressLibraryStatus(addrMap);
				addrMap.put("usestatus", "0");
				maotaiService.updateAddressLibraryStatus(addrMap);
				zhanghao.put("yuyuestatus", "0");
				maotaiService.updateZhanghaoYuYueStatus(zhanghao);
				return;
			}
			//{"data":{"endRow":1,"firstPage":1,"hasNextPage":false,"hasPreviousPage":false,"isFirstPage":true,"isLastPage":true,"lastPage":1,"list":[{"address":"江苏省南京市江宁区天禄大道1号翠屏城73栋805室","addressId":"1179370534174015495","applyTime":"2018-07-30 12:59:27","areaCode":"320115000000","buyCycleDay":null,"channelName":null,"cityCode":"320100000000","createTime":"2018-07-30 12:59:27","detailed":"天禄大道1号翠屏城73栋805室","equipId":null,"failureDay":null,"failureTime":null,"goodsId":"1180731799931808771","goodsName":"【茅台商城预约购买】贵州茅台酒（新飞天）53%vol 500ml（商品编号：741）","goodsPicture":"https://prod-oss.emaotai.cn/supplychain-dev/test/img/jXftfKCbpH.jpg","id":"1182370414635126790","itemId":"1180731799924468740","orderNo":null,"platformId":"1","provinceCode":"320000000000","receivePhone":"13372007847","receiver":"周亮亮","registPhone":"13372007847","reviewInfo":null,"reviewLevel":"0","reviewTime":null,"reviewer":null,"shopId":"1173773178264259584","skuKv":{"香型（多选）":"酱香"},"status":"1","userId":"3586409","userName":"nickboowen"}],"navigatePages":8,"navigatepageNums":[1],"nextPage":0,"orderBy":null,"pageNum":1,"pageSize":5,"pages":1,"prePage":0,"size":1,"startRow":1,"total":1},"resultCode":0,"resultMsg":"success"}
			JSONObject jObject2 = JSONObject.parseObject(mwc.getContent());
			JSONObject data2 = jObject2.getJSONObject("data");
			JSONArray data3 = data2.getJSONArray("list");
			boolean hasYuYue = false;
			String status = "";
			if (data3 == null || data3.size() == 0) {
				System.out.println(zhanghao.get("code")+" "+"账号没有预约--");
			}else{
				for (int i = 0; i < data3.size(); i++) {
					JSONObject temp = data3.getJSONObject(i);
					status = temp.getString("status");
					if("1".equals(status)||"3".equals(status)){
						//有登记过，但是网点还没有接单
						hasYuYue = true;
						break;
					}else if("6".equals(status)){
						//有登记过，但是没有网点接单
						continue;
					}else if("4".equals(status)){
						//有登记过，网点接单
						//查询订单
						//已接单是4
						hasYuYue = true;
					}else if("2".equals(status)){
						//有登记过，网点接单
						//查询订单
						//已接单是4
						continue;
					}
				}
			}
			if(hasYuYue){
				addrMap.put("usestatus", "0");
				maotaiService.updateAddressLibraryStatus(addrMap);
				return;
			}
			if("2".equals(status)){
				//修改地址
				/**
				 * deliveryName:康功栋
				address:日月天地大厦B座1901室跆拳道协会
				deliveryMobile:13112935251
				deliveryEmail:
				addressAlias:
				provinceCode:110000000000
				cityCode:110100000000
				areaCode:110106000000
				id:1181971912186910729
				defaultStatus:1
				 */
				Map<String, String> addressMap = new HashMap<String, String>();
				String telphone = zhanghao.get("phone") + "";
				// 从数据库中获取省市区
//				Map<String, Object> countryMap = maotaiService.getCountryRandomMY();
				
				String provinceid = addrMap.get("provinceid") + "";
				String provincename = addrMap.get("provincename") + "";
				String cityid = addrMap.get("cityid") + "";
				String cityname = addrMap.get("cityname") + "";
				String areaid = addrMap.get("areaid") + "";
				String areaname = addrMap.get("areaname") + "";
				String addressname = addrMap.get("name")+"";
				String address = addrMap.get("address")+"";
				System.out.println(provincename + cityname + areaname + address);

				
				Map<String, Object> personName = maotaiService.getPersonName();
				// String name =
				// personName.get("name")+""+chars.charAt((int)(Math.random() *
				// 26));//加上一个随机字母
				String name = personName.get("name") + "";// 加上一个随机字母
				int lou = CustomName.getRandomGuiZe();
				
				if("静安区".equals(areaname)){
//					address = addrMap.get("address") + "贵"+CustomName.getShtszf()+addressname+CustomName.getShtszf()
//							+ CustomName.getRandomGuiZe() + "栋" + + lou + "0"
//							+ CustomName.getNum1() + "室";
					address = addressname+CustomName.getShtszf() + "贵"+address+CustomName.getShtszf()
							+ CustomName.getRandomGuiZe() + "栋" + + lou + "0"
							+ CustomName.getNum1() + "室";
				}else{
//					address = addrMap.get("address") +CustomName.getShtszf()+ addressname+CustomName.getShtszf()
//							+ CustomName.getRandomGuiZe() + "栋" + + lou + "0"
//							+ CustomName.getNum1() + "室";
					address = addressname+CustomName.getShtszf() +address+CustomName.getShtszf()
							+ CustomName.getRandomGuiZe() + "栋" + + lou + "0"
							+ CustomName.getNum1() + "室";
				}
				address = address.replace(provincename, "");
				address = address.replace(cityname, "");
				address = address.replace(areaname, "");
				addressMap.put("deliveryName", name);
				addressMap.put("address", address);
				addressMap.put("deliveryMobile", telphone);
				addressMap.put("deliveryEmail", "");
				addressMap.put("addressAlias", "");
				addressMap.put("provinceCode", provinceid);
				addressMap.put("cityCode", cityid);
				addressMap.put("areaCode", areaid);
				addressMap.put("defaultStatus", "1");
				addressMap.put("id", addressId);
				mwc = hcu.sendHttpPutProxy(MaotaiString.ADDRESS_UPDATE_URL, mwc,
						addressMap,
						config,MaotaiString.ADDRESS_REFERER);
//				maotaiService.updateZhanghaoAddress(zhanghao);
			}else{
				addrMap.put("usestatus", "0");
				maotaiService.updateAddressLibraryStatus(addrMap);
			}
			//只是用来修改地址，预约需要刷脸
			/**
			 * 	memberId:3586409
				goodsId:1180731799931808771
				shopId:1173773178264259584
				itemId:1180731799924468740
				addressId:1179370534174015495
			 */
			
			//后期可以增加先访问预约页面
			//TODO
			//带cookie访问预约页面
			
//			hcu.sendHttpGetProxyIndex(MaotaiString.APPLY_BEGIN_URL, mwc, config, MaotaiString.APPLY_BEGIN_REFERER_URL);
//			Thread.sleep(1000);
//			//然后提交预约
//			Map<String, String> orderMap = new HashMap<String, String>();
//			orderMap.put("memberId", memberId);
//			orderMap.put("goodsId", Product741.GOODSID);
//			orderMap.put("shopId", Product741.SHOPID);
//			orderMap.put("itemId", Product741.ITEMID);
//			orderMap.put("addressId", addressId);
//			String applyUrl = MaotaiString.APPLY_URL_NEW;
//			hcu.sendHttpOptionProxy(applyUrl, mwc, config, MaotaiString.APPLY_REFERER);
//			mwc = hcu.sendHttpPostProxy(applyUrl, mwc,
//					orderMap,
//					config,MaotaiString.APPLY_REFERER);
//			if(mwc.getContent().contains("login")){
//				addrMap.put("usestatus", "0");
//				maotaiService.updateAddressLibraryStatus(addrMap);
//				zhanghao.put("yuyuestatus", "0");
//				maotaiService.updateZhanghaoYuYueStatus(zhanghao);
//				zhanghao.put("loginstatus", "0");
//				maotaiService.updateZhanghaoLoginStatus(zhanghao);
//				return;
//			}
//			if(mwc.getContent().contains("操作失败")){
//				addrMap.put("usestatus", "0");
//				maotaiService.updateAddressLibraryStatus(addrMap);
//				zhanghao.put("yuyuestatus", "4");
//				maotaiService.updateZhanghaoYuYueStatus(zhanghao);
//				return;
//			}if(mwc.getContent().contains("已结束")){
//				addrMap.put("usestatus", "0");
//				maotaiService.updateAddressLibraryStatus(addrMap);
//				zhanghao.put("yuyuestatus", "0");
//				maotaiService.updateZhanghaoYuYueStatus(zhanghao);
//				return;
//			}
//			System.out.println(zhanghao.get("code")+"提交预约情况--"+mwc.getContent());
//			
////			JSONObject jObject = JSONObject.parseObject(mwc.getContent());
//			//核对返回预约结果
//			
//			//提交预约之后，再访问下页面
//			Thread.sleep(1000);
//			if(mwc.getContent().contains("success")){
//				hcu.sendHttpGetProxyIndex(MaotaiString.APPLY_END_URL, mwc, config, MaotaiString.APPLY_END_REFERER_URL);
//			}
		} catch (Exception e) {
			System.out.println(zhanghao.get("code")+" : "+e.getMessage()+" throws updateAddress exception ");
			try {
				addrMap.put("usestatus", "0");
				maotaiService.updateAddressLibraryStatus(addrMap);
				zhanghao.put("yuyuestatus", "0");
				maotaiService.updateZhanghaoYuYueStatus(zhanghao);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}



}
